import { createAlova } from 'alova';
import AdapterUniapp from '@alova/adapter-uniapp';
import VueHook from 'alova/vue';
import { Result } from '@/types/request'
import { useUserStore } from '@/stores/user';

export const alovaInstance = createAlova({
	baseURL: 'http://localhost:8090',
	// baseURL: 'http://localhost:8094',
	...AdapterUniapp(),//uni-app的适配器
	timeout: 50000,//超时时间
	// cacheFor: {
	// 	GET: 0, // 关闭所有GET缓存
	// 	POST: 60 * 60 * 1000 // 设置所有POST缓存1小时
	// },
	cacheFor: null,//关闭全局缓存
	statesHook: VueHook,//启用Vue3的响应式（如：loading、data、error、生命周期等）
	beforeRequest(method) {
		//请求拦截器添加token等信息
		const userStore = useUserStore();// 获取用户store
		const token = userStore.token;
		if (token) {
			method.config.headers.authorization = token
		}
	},
	responded: {//响应拦截器
		onSuccess: async (response : UniApp.RequestSuccessCallbackResult | UniApp.UploadFileSuccessCallbackResult | UniApp.DownloadSuccessData, method) => {
			// console.log('响应接收:', response);
			const result = (response as UniApp.RequestSuccessCallbackResult).data as Result;
			if (!result.success) {
				uni.showToast({
					title: result.message,
					icon: 'none'
				})
				return Promise.reject(result); //使用reject可以是的async/await继续往下执行，从而执行try/catch中的错误代码
			}
			return result;
		},
		onError: (err, method) => {
			console.error('请求错误', err);
		},
		onComplete: async method => {
			// 处理请求完成逻辑
			console.log('onComplete：请求结束')
		}

	},

});